<template>
  <div>
    <div class="inline-form" style="width: 670px">
      <Form ref="form2" :model="form2" :rules="rules2" :label-width="120" style="display: block;">
        <FormItem
          v-for="(item, index) in form2.items"
          :key="index"
          :label="'外出地点 ' + item.index + ':'"
          :prop="'items.' + index + '.value'"
          :rules="{
            required: true,
            message: '外出地点 ' + item.index + ' 不能为空',
            trigger: 'blur',
          }"
        >
          <div>
            <i-input type="text" v-model="item.value"></i-input>
          </div>
          <div class="form-tip-1">
            <Icon
              type="ios-add-circle-outline"
              size="24"
              v-if="item.index == form2.items.length"
              @click="handleAdd"
            />
            <Icon
              type="ios-remove-circle-outline"
              size="24"
              v-if="item.index !== 1 && item.index == form2.items.length"
              @click="handleRemove(index)"
            />
          </div>
        </FormItem>
        <Row>
          <i-col span="12">
            <FormItem prop="startDate" label="开始日期:">
              <DatePicker
                type="date"
                class="form-input-small"
                v-model="form2.startDate"
                placeholder="请选择日期"
                @on-change="calOutTime"
                format="yyyy-MM-dd"
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem prop="startTime" label="开始时间:">
              <TimePicker
                type="time"
                format="HH:mm"
                :clearable="false"
                :confirm="false"
                placeholder="请选择时间"
                @on-change="calOutTime"
                v-model="form2.startTime"
                :editable="false"
              ></TimePicker>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="12">
            <FormItem prop="endDate" label="结束日期:">
              <DatePicker
                type="date"
                class="form-input-small"
                v-model="form2.endDate"
                placeholder="请选择日期"
                @on-change="calOutTime"
                format="yyyy-MM-dd"
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem prop="endTime" label="结束时间:">
              <TimePicker
                type="time"
                format="HH:mm"
                :clearable="false"
                :confirm="false"
                placeholder="请选择时间"
                @on-change="calOutTime"
                v-model="form2.endTime"
                :editable="false"
              ></TimePicker>
            </FormItem>
          </i-col>
        </Row>
        <FormItem prop="outType" label="外出类型:">
          <Select
            class="form-input-small"
            v-model="form2.outType"
            @on-change="calTime"
            clearable
          >
            <Option v-for="item in outList" :key="item.key" :value="item.key">{{
              item.value
            }}</Option>
          </Select>
        </FormItem>
        <Row>
          <i-col span="18">
            <FormItem prop="outHour" label="外出时间:">
              <i-input
                type="text"
                class="form-input-small"
                v-model="form2.outHour"
                disabled
              >
                <div
                  slot="suffix"
                  style="line-height: 32px; color: rgba(0, 0, 0, 0.43)"
                >
                  天数
                </div>
              </i-input>
            </FormItem>
          </i-col>
        </Row>
        <FormItem prop="outReason" label="外出事由:">
          <i-input
            type="textarea"
            v-model="form2.outReason"
            :rows="4"
            placeholder="请输入"
          ></i-input>
        </FormItem>
        <FormItem prop="leaveFile" label="说明附件:">
          <Uploadv
            multiple
            ref="upload"
            type="drag"
            :before-upload="handleUpload"
            :show-upload-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadFail"
            :headers="{
              Authorization: '',
            }"
            name="multipartFile"
            :data="{
              applyNo: '',
            }"
            :action="action"
          >
            <Icon
              type="ios-cloud-upload"
              size="52"
              style="color: #3399ff"
            ></Icon>
            <p>点击或将文件拖拽到这里上传</p>
            <p style="color: rgba(0, 0, 0, 0.43)">
              支持扩展名：.rar .zip .doc .docx .pdf .jpg...
            </p>
          </Uploadv>
          <div v-for="(item, index) in file" :key="index">
            <div>
              <Icon type="md-attach" style="transform: rotate(90deg)" />
              &nbsp;{{ item.name }}
              <span @click="delectFile(item.keyID)" class="deleteFile">X</span>
            </div>
          </div>
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            style="width: 74px"
            @click="handleSubmit('form2')"
            :loading="submitLoading"
            >提交</Button
          >
          <Button
            type="default"
            style="width: 74px; margin-left: 25px"
            @click="previousStep"
            v-if="previousStepShow"
            >上一步</Button
          >
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    applyInfo: {
      type: String,
    },
  },
  data() {
    const validateStartDate = (rule, value, callback) => {
      if (this.form2.startDate == "" || this.form2.endDate == "") {
      } else {
        this.$refs.form2.validateField("endTime");
      }

      callback();
    };
    const validateEndDate = (rule, value, callback) => {
      let startD = new Date(this.form2.startDate).getTime();
      let endD = new Date(this.form2.endDate).getTime();
      let startT = new Date("1970-01-01 " + this.form2.startTime).getTime();
      let endT = new Date("1970-01-01 " + this.form2.endTime).getTime();
      let start = startD + startT;
      let end = endD + endT;
      if (this.form2.startDate == "" || this.form2.endDate == "") {
      } else if (start >= end) {
        callback(new Error("结束日期需大于开始时间"));
      } else {
      }

      callback();
    };
    return {
      form2: {
        items: [
          {
            value: "",
            index: 1,
            status: 1,
          },
        ],
        // startDate: '',
        // endDate: '',
        // startTime: '',
        // endTime: '',
        startDate: new Date(),
        endDate: new Date(),
        startTime: new Date().getHours() + ":" + new Date().getMinutes(),
        endTime: new Date().getHours() + ":" + new Date().getMinutes(),
        outType: "",
        outHour: "",
        outReason: "",
      },
      rules2: {
        startDate: [
          { required: true, message: "开始时间不能为空" },
          { validator: validateStartDate, trigger: "blur" },
          { validator: validateStartDate, trigger: "change" },
        ],
        endDate: [
          { required: true, message: "结束时间不能为空" },
          { validator: validateStartDate, trigger: "blur" },
          { validator: validateStartDate, trigger: "change" },
        ],
        startTime: [
          { required: true, message: "结束时间不能为空" },
          { validator: validateStartDate, trigger: "blur" },
          { validator: validateStartDate, trigger: "change" },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空" },
          { validator: validateEndDate, trigger: "blur" },
          { validator: validateEndDate, trigger: "change" },
        ],
        outType: [{ required: true, message: "外出类型不能为空" }],
        outHour: [{ required: true, message: "外出时长不能为空" }],
      },
      outList: [],
      applyNo: "",
      previousStepShow: true,
      file: [],
      deleteFiles: [],
      fileIndex: 0,
      submitLoading: false,
      action: "",
    };
  },
  methods: {
    // 外出地点增加input
    handleAdd() {
      this.form2.items.push({
        value: "",
        index: this.form2.items.length + 1,
        status: 1,
      });
    },
    // 外出地点删除input
    handleRemove(index) {
      this.form2.items.splice(index, 1);
      // this.form2.items[index].status = 0;
    },

    // 外出类型接口
    getOutType() {
      this.api.getOutType().then((res) => {
        if (res.code == 200 && res.data != null) {
          this.outList = res.data.data;
        }
      });
      // this.action = sessionStorage.getItem("userIp") + "api/fileupload/up";
      this.action = "/scrm-gateway/scrm-uer/api/fileupload/up";
    },

    // 重置表单
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    // 外出时间计算
    calOutTime() {
      console.log(this.form2, "qingqiu");
      this.time(this.form2.startDate, this.form2.startTime);
      if (this.form2.startDate != "" && this.form2.startTime == "") {
        this.form2.startTime = "00:00";
      }
      if (this.form2.endDate != "" && this.form2.endTime == "") {
        this.form2.endTime = "00:00";
      }
      let startD = new Date(this.form2.startDate).getTime();
      let endD = new Date(this.form2.endDate).getTime();
      let startT = new Date("1970-01-01 " + this.form2.startTime).getTime();
      let endT = new Date("1970-01-01 " + this.form2.endTime).getTime();
      let start = startD + startT;
      let end = endD + endT;
      // console.log(startD,"startD");
      // console.log(endD,"endD");
      // console.log(startT,"startT");
      // console.log(endT,"endT");
      if (this.form2.startDate == "" || this.form2.endDate == "") {
      } else if (start > end) {
        this.form2.outHour = "";
      } else {
        let dat = new Date(start).toJSON();
        let date = new Date(+new Date(dat) + 16 * 3600 * 1000).toISOString();
        let d1 = new Date(end).toJSON();
        let date1 = new Date(+new Date(d1) + 16 * 3600 * 1000).toISOString();
        let obj = {
          applyType: "2",
          // startTime: date,
          // endTime: date1,
          startTime: this.time(this.form2.startDate, this.form2.startTime),
          endTime: this.time(this.form2.endDate, this.form2.endTime),
          startTimeSolt: "",
          endTimeSolt: "",
        };
        this.api.idWorkDay(obj).then((res) => {
          if (res.code == 200 && res.data != null) {
            this.form2.outHour = res.data;
          } else {
            this.$Message.error(res.msg);
          }
        });
      }
    },

    //提交
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let places = [];
          this.form2.items.forEach((element) => {
            places.push(element.value);
          });
          let startD = new Date(this.form2.startDate).getTime();
          let endD = new Date(this.form2.endDate).getTime();
          console.log(this.form2.endTime, "endTime");
          console.log(this.form2.startTime, "startTime");
          let startT = new Date("1970-01-01 " + this.form2.startTime).getTime();
          let endT = new Date("1970-01-01 " + this.form2.endTime).getTime();
          console.log(startT, "startT");
          console.log(endT, "endT");
          let start = startD + startT;
          let end = endD + endT;

          let place = places.join(",");

          let dat = new Date(start).toJSON();
          let date =
            new Date(+new Date(dat) + 16 * 3600 * 1000)
              .toISOString()
              .substring(0, 10) +
            " " +
            new Date(+new Date(dat) + 16 * 3600 * 1000)
              .toISOString()
              .substring(11, 17);
          console.log(date, "date");
          let d1 = new Date(end).toJSON();
          let date1 =
            new Date(+new Date(d1) + 16 * 3600 * 1000)
              .toISOString()
              .substring(0, 10) +
            " " +
            new Date(+new Date(d1) + 16 * 3600 * 1000)
              .toISOString()
              .substring(11, 17);

          let obj = {
            uid: 1,
            place: place,
            startTime: this.time(this.form2.startDate, this.form2.startTime),
            endTime: this.time(this.form2.endDate, this.form2.endTime),
            detail: this.form2.outType,
            duration: this.form2.outHour,
            reason: this.form2.outReason,
            applyNo: this.applyNo,
          };
          console.log(obj, "obj");
          // return
          // 删除文件
          if (this.deleteFiles.length > 0) {
            this.deleteFiles.forEach((element) => {
              if (element.id) {
                let obj = {
                  id: element.id,
                };
                this.api.deleteAttachment(obj).then((res) => {
                  if (res.code == 200) {
                  } else {
                    this.$Message.error(res.msg);
                    return false;
                  }
                });
              }
            });
          }
          // 提交
          this.api.addUerApplyOut(obj).then((res) => {
            if (res.code == 200 && res.data != null) {
              if (res.data.applyNo) {
                this.$refs.upload.data.applyNo = res.data.applyNo;
                this.applyNo = res.data.applyNo;
              } else {
                this.$Message.error("文件上传失败");
              }
              this.upload();
            } else {
              this.submitLoading = false;
              this.$Message.error(res.msg);
            }
          });
        } else {
          this.$Message.error("信息填写有误");
        }
      });
    },

    // 回退到上一步
    previousStep() {
      this.$emit("currentChanged", "0");
    },

    // 保存需要上传的文件
    handleUpload(file) {
      // 保存需要上传的文件
      let keyID = Math.random().toString().substr(2);
      file["keyID"] = keyID;
      this.file.push(file);
      return false;
    },
    // 删除文件
    delectFile(keyID) {
      this.file = this.file.filter((item) => {
        if (item.keyID == keyID) {
          // 保存到删除文件数组
          if (item.id) {
            this.deleteFiles.push(item);
          }
        }
        return item.keyID != keyID;
      });
    },
    // 上传文件
    upload() {
      this.$refs.upload.headers.Authorization =
        sessionStorage.getItem("credentials");
      if (this.file.length > 0) {
        for (let i = 0; i < this.file.length; i++) {
          let item = this.file[i];
          if (item.id) {
            // 重新提交原文件不上传
            this.fileIndex++;
            // 如果全部是原文件
            if (this.fileIndex == this.file.length) {
              this.submitLoading = false;
              this.file = [];
              this.$Message.success("外出申请提交成功");
              // 向父组件传递事件
              this.$emit("currentChanged", "2");
              // 向父组件传递applyNo查询审批流程
              this.$emit("currentChanged", this.applyNo);
            }
          } else {
            this.$refs.upload.post(item);
          }
        }
      } else {
        this.submitLoading = false;
        this.$Message.success("外出申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
    },
    // 文件上传成功
    uploadSuccess(response, file, fileList) {
      this.fileIndex++;
      this.$Message.success(response.data[0].name + "上传成功");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$Message.success("外出申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
      return true;
    },

    // 文件上传失败
    uploadFail(response, file, fileList) {
      this.fileIndex++;
      this.$Message.error(response.data[0].name + "上传失败");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$Message.success("外出申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
      return false;
    },

    // 填充表单
    formFill() {
      if (this.applyInfo != null) {
        this.previousStepShow = false;
        this.applyNo = this.applyInfo.applyNo;
        let obj = {
          applyNo: this.applyInfo.applyNo,
        };
        this.api.getApplyInfo(obj).then((res) => {
          if (res.code == 200 && res.data != null) {
            // 带出地点
            let places11 = res.data.places.replace(/\s*/g, "").split(/\(\d\)/g);
            // if(places.length>1){

            // }
            // places.splice(0, 1);
            // this.form2.items = []
            let places = [];
            places11.map((item) => {
              if (item != "") {
                places.push(item);
              }
            });
            for (let i = 0; i < places.length; i++) {
              if (i != 0) {
                this.form2.items.push({
                  value: places[i],
                  index: this.form2.items.length + 1,
                  status: 1,
                });
              } else {
                this.form2.items[0].value = places[0];
              }
            }
            this.form2.startDate = res.data.startTime;
            this.form2.endDate = res.data.endTime;
            this.form2.startTime = res.data.startTime.substring(12, 22);
            this.form2.endTime = res.data.endTime.substring(12, 22);
            this.outList.forEach((element) => {
              if (element.value == res.data.detail) {
                this.form2.outType = element.key;
              }
            });
            this.form2.outHour = res.data.duration;
            // 理由和文件不是必填
            if (res.data.reason) {
              this.form2.outReason = res.data.reason;
            }
            if (res.data.uerAttachment.length > 0) {
              res.data.uerAttachment.forEach((element) => {
                let file = {
                  id: element.id,
                  name: element.fileName,
                };
                this.handleUpload(file);
              });
            }
            // //20201215
            // this.api.getApplyInfo({
            //   agentcode:'', //还没加，待联调
            //   messageid:obj.applyNo,
            //   messagetype:3
            // }).then(res => {
            //   console.log(res)
            // })
          } else {
            this.$Message.error(res.msg);
          }
        });
      }
    },
    // 时间处理
    time(value, t) {
      let date = new Date(value);
      let getMonth = (date.getMonth() + 1).toString();
      let getDate = date.getDate().toString();
      return `${date.getFullYear()}-${
        getMonth.length === 1 ? "0" + getMonth : getMonth
      }-${getDate.length === 1 ? "0" + getDate : getDate} ${t}`;
    },
  },
  mounted() {
    this.getOutType();
    // 填充表单
    this.formFill();
  },
  beforeDestroy() {
    this.form2 = null;
    this.rules2 = null;
    this.outList = null;
    this.applyNo = null;
    this.previousStepShow = null;
    this.file = null;
    this.deleteFiles = null;
    this.fileIndex = null;
    this.submitLoading = null;
    this.action = null;
  },
};
</script>

<style lang="less" scoped>
@import "./index";
</style>


<style>
textarea.ivu-input {
  resize: none;
}
</style>